package com.magicsoft.share.ui.exchange;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.magicsoft.share.R;
import com.magicsoft.share.adapter.exchange.SettlementAdapter;
import com.magicsoft.share.base.BaseActivity;
import com.magicsoft.share.bean.exchange.AddressDefault;
import com.magicsoft.share.bean.exchange.Freight;
import com.magicsoft.share.bean.exchange.GoodsSubmit;
import com.magicsoft.share.bean.exchange.SubmitOrder;
import com.magicsoft.share.bean.my.Address;
import com.magicsoft.share.constant.Constant;
import com.magicsoft.share.customview.SwipeItemLayout;
import com.magicsoft.share.presenter.exchange.SettlementPresenter;
import com.magicsoft.share.ui.main.InputMobileActivity;
import com.magicsoft.share.ui.my.AddressActivity;
import com.magicsoft.share.utils.DensityUtils;
import com.magicsoft.share.utils.ToastUtils;
import com.magicsoft.share.view.exchange.ISettlementView;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class SettlementActivity extends BaseActivity<ISettlementView, SettlementPresenter> implements ISettlementView {


    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.ibtn_left)
    ImageButton ibtnLeft;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ibtn_right)
    ImageButton ibtnRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.layout_address)
    RelativeLayout layoutAddress;
    @BindView(R.id.recyclerView)
    SwipeMenuRecyclerView recyclerView;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.btn_buy)
    Button btnBuy;
    private AlertDialog alertDialog;
    private String goodsStr;
    private int orderAmount;
    private ArrayList<GoodsSubmit> goodsList;
    private SettlementAdapter settlementAdapter;
    private Freight mFreight;
    private TextView freightText;
    private int freightStr = 0;
    private int balance;
    private TextView tv_money;
    private TextView tv_balance;
    private TextView tv_forget_password;
    private TextView tv_error;
    private String app_user_name;
    private String phone;
    private String address;
    private EditText edt;
    private int isDirect = 1;
    private long lockStockId;
    private int type;


    @Override
    public SettlementPresenter initPresenter() {
        return new SettlementPresenter();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter.addressDefault();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_settlement;
    }

    @Override
    public void initData() {
        isDirect = getIntent().getIntExtra("isDirect", 1);
        goodsStr = getIntent().getStringExtra("goodsStr");
        orderAmount = getIntent().getIntExtra("orderAmount", -1);
        goodsList = ((ArrayList<GoodsSubmit>) getIntent().getSerializableExtra("GoodsList"));
        type=getIntent().getIntExtra("tyoe",-1);
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void initView() {
        tvTitle.setText("确认订单");

        initRV();

        tvNum.setText("共"+(settlementAdapter.getItemCount()-1)+"件");

            tvPrice.setText(orderAmount+"");



    }

    @Override
    public void requestData() {

        mPresenter.freight();

    }

    @OnClick({R.id.ibtn_left, R.id.layout_address, R.id.btn_buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_left:
                finish();
                break;
            case R.id.layout_address:
                startActivityForResult(new Intent(this, AddressActivity.class), Constant.REFRESH_UI);
                break;
            case R.id.btn_buy:
                if (app_user_name == null || app_user_name.equals("") || phone == null || phone.equals("") || address.equals("") || address == null) {
                    ToastUtils.showToast(this, "请选择有效收货地址");
                } else {
                    if (orderAmount != -1) {
                        mPresenter.submitOrder(orderAmount, goodsStr);
                    }
                }


                break;
        }
    }

    private void initByDialog() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_settlement, null);
        tv_money = inflate.findViewById(R.id.tv_money);
        int money = orderAmount + freightStr;
//        if(money<100){
            tvPrice.setText(money + "");
//        }else {
//            tvPrice.setText(money + "");
//        }

        tv_balance = inflate.findViewById(R.id.tv_balance);
        tv_balance.setText("" + balance);
        tv_forget_password = inflate.findViewById(R.id.tv_forget_password);
        tv_forget_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(SettlementActivity.this, InputMobileActivity.class));
            }
        });
        tv_error = inflate.findViewById(R.id.tv_error);
        edt = inflate.findViewById(R.id.edt);
        inflate.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        inflate.findViewById(R.id.btn_next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String password = edt.getText().toString();
                if (password == null || password.equals("")) {
                    ToastUtils.showToast(SettlementActivity.this, "请输入密码");
                } else {
                    mPresenter.addOrder(app_user_name, phone, orderAmount, address, freightStr, goodsStr, password, isDirect, lockStockId);
                }
            }
        });
        alertDialog = new AlertDialog.Builder(this).setView(inflate).create();
        alertDialog.setCancelable(false);
        alertDialog.show();
    }


    private void initRV() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(this));

        settlementAdapter = new SettlementAdapter(R.layout.item_settlement);
        settlementAdapter.setNewData(goodsList);

        recyclerView.setAdapter(settlementAdapter);

        View bottom = LayoutInflater.from(this).inflate(R.layout.item_settlement_bottom, recyclerView, false);
        freightText = ((TextView) bottom.findViewById(R.id.textView));
        settlementAdapter.addFooterView(bottom);

        recyclerView.addItemDecoration(new DefaultItemDecoration(getResources().getColor(R.color.bg), 0, DensityUtils.dp2px(this, 0.8f), BaseQuickAdapter.FOOTER_VIEW));
    }

    @Override
    public void submitOrderSuccess(SubmitOrder submitOrder) {
        balance = submitOrder.getBalance();
        lockStockId = submitOrder.getLockStockId();
        if (submitOrder.getStockStatus() == 1) {
            initByDialog();
        } else {
            settlementAdapter.refreshData(submitOrder);
        }

    }

    @Override
    public void freightSuccess(Freight freight) {

        mFreight = freight;
        if (orderAmount >= freight.getFreight_condition()) {
            freightStr = 0;
            freightText.setText("运费0金币");
        } else {
            freightText.setText("运费" + freight.getFreight_amount() + "金币");
            freightStr = freight.getFreight_amount();
            if(orderAmount<=100){
                if(type==1) {
                    tvPrice.setText((orderAmount + freight.getFreight_amount()) + "");
                }else {
                    tvPrice.setText(orderAmount+"");
                }
            }
            else {
                tvPrice.setText(orderAmount);
            }
        }
        if(settlementAdapter.getData().size()==0){
            Log.e("detel","df"+(settlementAdapter.getItemCount()-1));
            recyclerView.setBackground(getResources().getDrawable(R.drawable.icon_nodata));
        }else {
            recyclerView.setBackgroundColor(getResources().getColor(R.color.white));
        }
    }

    @Override
    public void addressDefaultSuccess(AddressDefault aDefault) {
        app_user_name = aDefault.getApp_user_name();
        phone = aDefault.getPhone();
        address = aDefault.getAddress();
        tvName.setText("收货人：" + app_user_name);
        tvMobile.setText(phone);
        tvAddress.setText("收货地址：" + address);
    }

    @Override
    public void addOrderSuccess() {
        ToastUtils.showToast(this, "支付成功");
        alertDialog.dismiss();
        finish();
    }

    @Override
    public void addorderFail(String errorMsg) {

        if (errorMsg.equals("密码不正确")) {
            tv_error.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("lyf", "onActivityResult: ");
        if (requestCode == Constant.REFRESH_UI) {
            if (resultCode == RESULT_OK) {
                Address address = (Address) data.getSerializableExtra("address");
                app_user_name = address.getApp_user_name();
                phone = address.getPhone();
                this.address = address.getRegion() + address.getAddress_detail();
                tvName.setText("收货人：" + app_user_name);
                tvMobile.setText(phone);
                tvAddress.setText("收货地址：" + this.address);
            }
        }
    }


}
